#include "appengine.h"

AppEngine *AppEngine::m_instance = nullptr;
QMutex AppEngine::m_mutex;

AppEngine::AppEngine(QObject *parent)
    : QQmlApplicationEngine{parent}
{
    m_ModbusTCP = ModbusTCP_Class::getInstance();
    m_History = HistoryModel::getInstance();

    // 初始化参数管理类实例
    m_ProcessDataManager = new ProcessDataManager(this);
    m_ProcessModel = new ParameterModel(this);
    m_ProcessItem = new ParameterItem(this);

    m_Init = InitData::getInstance();
    m_Scanner = ScannerControl::getInstance();
    m_Printer = PrinterControl::getInstance();

    m_Scanner->set_Connect_Parameters(m_Init->scanner_Port(),
                                      m_Init->scanner_BaudRate(),
                                      m_Init->scanner_DataBit(),
                                      m_Init->scanner_Parity(),
                                      m_Init->scanner_StopBit());

    m_Printer->set_Connect_Parameters(m_Init->printer_Port(),
                                      m_Init->printer_BaudRate(),
                                      m_Init->printer_DataBit(),
                                      m_Init->printer_Parity(),
                                      m_Init->printer_StopBit());

    m_Scanner->connet_To_Device();
    m_Printer->connet_To_Device();



    // 注册
    registerType();

    QObject::connect(m_ModbusTCP, &ModbusTCP_Class::warningHistoryUpdated,
                     m_History, &HistoryModel::updateHistory);
    QObject::connect(m_ModbusTCP, &ModbusTCP_Class::warningUpdated,
                     m_History, &HistoryModel::updateWarning);


    QObject::connect(m_Scanner,&ScannerControl::scanner_Recv_Data_Signal,m_Scanner,&ScannerControl::test_Recv_Slots);
    QObject::connect(m_Scanner,&ScannerControl::scanner_Recv_Data_Signal,m_ModbusTCP,&ModbusTCP_Class::scanner_write_Aim_Location);

}

AppEngine *AppEngine::getInstance()
{
    if (!m_instance) {
        QMutexLocker locker(&m_mutex);
        if (!m_instance) {
            m_instance = new AppEngine();
        }
    }
    return m_instance;
}

void AppEngine::destroyInstance()
{
    // 若实例存在，则删除（触发析构函数）
    if (m_instance != nullptr) {
        delete m_instance;  // 调用 ~AppEngine()
        m_instance = nullptr;  // 置空，避免重复删除
        qDebug() << "AppEngine 实例已销毁";
    }
}

AppEngine::~AppEngine()
{
    m_Init->deleteLater();
    delete m_ProcessDataManager;
    delete m_ProcessModel;
    delete m_ProcessItem;
}

void AppEngine::registerType()
{

    this->rootContext()->setContextProperty("Cpp_PLC", m_ModbusTCP);
    this->rootContext()->setContextProperty("warningHistory", m_History);

    this->rootContext()->setContextProperty("processManager", m_ProcessDataManager);
    this->rootContext()->setContextProperty("processModel", m_ProcessModel);
    this->rootContext()->setContextProperty("processItem", m_ProcessItem);

    this->rootContext()->setContextProperty("initData",m_Init);
    this->rootContext()->setContextProperty("Cpp_Printer",m_Printer);



}
